// src/utils/mqttClient.ts
import mqtt from 'mqtt'

let client: mqtt.MqttClient | null = null

export function createMqttClient(): mqtt.MqttClient {
  const {
    VITE_MQTT_HOST,
    VITE_MQTT_PORT,
    VITE_MQTT_USERNAME,
    VITE_MQTT_PASSWORD,
    VITE_MQTT_CLIENT_ID,
    VITE_MQTT_PATH
  } = import.meta.env

  const url = `ws://${VITE_MQTT_HOST}:${VITE_MQTT_PORT}${VITE_MQTT_PATH}`

  if (client) return client

  client = mqtt.connect(url, {
    clientId: VITE_MQTT_CLIENT_ID,
    username: VITE_MQTT_USERNAME,
    password: VITE_MQTT_PASSWORD,
    clean: true,
    connectTimeout: 4000,
    reconnectPeriod: 1000
  })

  return client
}

export function getMqttClient(): mqtt.MqttClient | null {
  return client
}
